package com.example.smartpark.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.smartpark.dto.UserAuditDTO;
import com.example.smartpark.dto.UserAuditQueryDTO;
import com.example.smartpark.exception.BusinessException;
import com.example.smartpark.mapper.UserAuditMapper;
import com.example.smartpark.mapper.UserMapper;
import com.example.smartpark.mapper.VehicleMapper;
import com.example.smartpark.model.User;
import com.example.smartpark.model.UserAudit;
import com.example.smartpark.model.Vehicle;
import com.example.smartpark.service.UserAuditService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户审核服务实现类
 */
@Slf4j
@Service
public class UserAuditServiceImpl extends ServiceImpl<UserAuditMapper, UserAudit> implements UserAuditService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private VehicleMapper vehicleMapper;

    private static final SimpleDateFormat DATE_FORMATTER = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public IPage<UserAuditDTO> getUserAuditPage(UserAuditQueryDTO queryDTO) {
        log.info("分页查询用户审核列表: {}", queryDTO);
        
        Page<UserAudit> page = new Page<>(queryDTO.getPage(), queryDTO.getSize());
        LambdaQueryWrapper<UserAudit> queryWrapper = new LambdaQueryWrapper<>();
        
        // 添加查询条件
        if (queryDTO.getUserId() != null) {
            queryWrapper.eq(UserAudit::getUserId, queryDTO.getUserId());
        }
        
        if (queryDTO.getAuditType() != null) {
            queryWrapper.eq(UserAudit::getAuditType, queryDTO.getAuditType());
        }
        
        if (queryDTO.getStatus() != null) {
            queryWrapper.eq(UserAudit::getStatus, queryDTO.getStatus());
        }
        
        // 按创建时间倒序排序
        queryWrapper.orderByDesc(UserAudit::getCreatedAt);
        
        // 执行分页查询
        Page<UserAudit> resultPage = page(page, queryWrapper);
        
        // 转换为DTO并填充额外信息
        Map<Integer, User> userCache = new HashMap<>(); // 用户缓存，避免重复查询
        
        List<UserAuditDTO> records = resultPage.getRecords().stream()
                .map(audit -> {
                    UserAuditDTO dto = new UserAuditDTO();
                    BeanUtils.copyProperties(audit, dto);
                    
                    // 额外处理时间格式等
                    if (audit.getAuditTime() != null) {
                        dto.setAuditTime(audit.getAuditTime().toInstant()
                                .atZone(java.time.ZoneId.systemDefault())
                                .toLocalDateTime());
                    }
                    
                    return dto;
                })
                .collect(Collectors.toList());
        
        // 构建返回结果
        Page<UserAuditDTO> dtoPage = new Page<>(resultPage.getCurrent(), resultPage.getSize(), resultPage.getTotal());
        dtoPage.setRecords(records);
        
        return dtoPage;
    }

    @Override
    public UserAuditDTO getUserAuditById(Integer id) {
        log.info("获取用户审核详情: {}", id);
        
        UserAudit userAudit = this.getById(id);
        if (userAudit == null) {
            throw new BusinessException("审核记录不存在");
        }
        
        UserAuditDTO dto = convertToDTO(userAudit);
        fillUserInfo(dto);
        
        return dto;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserAuditDTO createUserAudit(UserAuditDTO userAuditDTO) {
        log.info("创建用户审核记录: {}", userAuditDTO);
        
        UserAudit userAudit = new UserAudit();
        BeanUtils.copyProperties(userAuditDTO, userAudit);
        
        // 设置默认状态
        userAudit.setStatus(0); // 待审核
        
        // 保存
        if (!this.save(userAudit)) {
            throw new BusinessException("创建审核记录失败");
        }
        
        return convertToDTO(userAudit);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserAuditDTO processUserAudit(Integer id, Integer status, String remark, Integer auditorId) {
        log.info("处理用户审核: id={}, status={}, remark={}, auditorId={}", id, status, remark, auditorId);
        
        // 检查审核记录是否存在
        UserAudit userAudit = this.getById(id);
        if (userAudit == null) {
            throw new BusinessException("审核记录不存在");
        }
        
        // 检查状态是否有效
        if (status != 1 && status != 2) {
            throw new BusinessException("无效的审核状态");
        }
        
        // 更新审核信息
        userAudit.setStatus(status);
        userAudit.setRemark(remark);
        userAudit.setAuditorId(auditorId);
        userAudit.setAuditTime(new Date());
        
        // 保存更新
        if (!this.updateById(userAudit)) {
            throw new BusinessException("更新审核记录失败");
        }
        
        // 处理相应业务逻辑
        handleAuditBusiness(userAudit);
        
        UserAuditDTO dto = convertToDTO(userAudit);
        fillUserInfo(dto);
        
        return dto;
    }
    
    /**
     * 处理审核后的业务逻辑
     *
     * @param userAudit 审核记录
     */
    private void handleAuditBusiness(UserAudit userAudit) {
        if (userAudit.getAuditType() == 1) {
            // 用户注册审核
            handleUserRegisterAudit(userAudit);
        } else if (userAudit.getAuditType() == 2) {
            // 车辆审核
            handleVehicleAudit(userAudit);
        }
    }
    
    /**
     * 处理用户注册审核
     *
     * @param userAudit 审核记录
     */
    private void handleUserRegisterAudit(UserAudit userAudit) {
        if (userAudit.getUserId() == null) {
            return;
        }
        
        // 获取用户
        User user = userMapper.selectById(userAudit.getUserId());
        if (user == null) {
            return;
        }
        
        // 更新用户状态
        if (userAudit.getStatus() == 1) {
            // 审核通过
            user.setStatus(1); // 启用用户
        } else if (userAudit.getStatus() == 2) {
            // 审核拒绝
            user.setStatus(0); // 禁用用户
        }
        
        userMapper.updateById(user);
    }
    
    /**
     * 处理车辆审核
     *
     * @param userAudit 审核记录
     */
    private void handleVehicleAudit(UserAudit userAudit) {
        if (userAudit.getRelatedId() == null) {
            return;
        }
        
        // 获取车辆
        Vehicle vehicle = vehicleMapper.selectById(userAudit.getRelatedId());
        if (vehicle == null) {
            return;
        }
        
        // 更新车辆状态
        vehicle.setStatus(userAudit.getStatus());
        vehicleMapper.updateById(vehicle);
    }
    
    /**
     * 将实体转换为DTO
     */
    private UserAuditDTO convertToDTO(UserAudit userAudit) {
        UserAuditDTO dto = new UserAuditDTO();
        BeanUtils.copyProperties(userAudit, dto);
        
        // 转换Date类型到LocalDateTime
        if (userAudit.getAuditTime() != null) {
            dto.setAuditTime(userAudit.getAuditTime().toInstant()
                    .atZone(java.time.ZoneId.systemDefault())
                    .toLocalDateTime());
        }
        
        return dto;
    }
    
    /**
     * 填充用户信息
     *
     * @param dto 用户审核DTO
     */
    private void fillUserInfo(UserAuditDTO dto) {
        // 根据用户ID获取用户信息
        User user = userMapper.selectById(dto.getUserId());
        // 用户信息字段已从DTO中移除，无需再设置
    }
} 